﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Intergr8.Data;

using Intergr8.Data.CRMDataSource.CrmSdk;
using Intergr8.Data.CRMDataSource.CrmMetadataSdk;


namespace Intergr8.Data.CRMDataSource
{
    public class CRMDataProvider : DataProvider
    {

        CrmService _service;

        /// <summary>
        /// Initialise the CRM Connection and provider initialisation
        /// </summary>
        /// <param name="name"></param>
        /// <param name="config"></param>
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {

            try
            {
                System.Diagnostics.Trace.WriteLine("Initialising CSVDataProvider");
                
                // Initialise the base first
                base.Initialize(name, config);

                // Set up the CRM Service.  
                _service = CrmServiceUtility.GetCrmService(config["crmServerUrl"],config["orgName"]);
                _service.PreAuthenticate = true;

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("CRMDataProvider Exception " + ex.Message);
                throw ex;
            }
            finally
            {
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override System.Data.DataTable Fetch()
        {
            #region Fetch Sales records     
            // Retrieve all sales the user has access to
            QueryExpression queryInvoice = new QueryExpression();

            // Set the Query to retrieve invoices
            queryInvoice.EntityName = EntityName.invoice.ToString();

            // Create the Request Object
            RetrieveMultipleRequest retrieveInvoices = new RetrieveMultipleRequest();

            // Set the Request Object's Properties
            retrieveInvoices.Query = queryInvoice;

            // Execute the Request
            RetrieveMultipleResponse retrievedInvoices = (RetrieveMultipleResponse)_service.Execute(retrieveInvoices);

            #region Debug
            foreach (BusinessEntity be in retrievedInvoices.BusinessEntityCollection.BusinessEntities)
            {
                invoice inv = (invoice)be;
                System.Diagnostics.Trace.WriteLine(inv.invoicenumber + " " + inv.name + " " + inv.totalamount.Value.ToString());
            }

            #endregion
            #endregion

            #region Build DataTable
            // Build a DataTable containing the Region and Amount

            System.Data.DataTable dTable = new System.Data.DataTable();

            #endregion

            #region Generate results data
            // Return the DataTable Groued and summed by Region
            #endregion

            // Return the data
            return dTable;

            #region Retrieve all accounts user has read access to
            //// Create the Query Expression
            //QueryExpression query1 = new QueryExpression();

            //// Set the Query to retrieve accounts
            //query1.EntityName = EntityName.account.ToString();

            //// Create the Request Object
            //RetrieveMultipleRequest retrieve1 = new RetrieveMultipleRequest();

            //// Set the Request Object's Properties
            //retrieve1.Query = query1;

            //// Execute the Request
            //RetrieveMultipleResponse retrieved1 = (RetrieveMultipleResponse)service.Execute(retrieve1);
            //#endregion

            //#region Return Accounts whose owner's last name is not Cannon
            //// Creates a column set holding the names of the columns to be retreived
            //ColumnSet cols = new ColumnSet();

            //// Set the ColumnSet's properties
            //cols.Attributes = new string[] { "name", "accountid" };

            //// Create the ConditionExpression
            //ConditionExpression condition = new ConditionExpression();

            //// Set the Condition for the Retrieval to be when the account's owner's last name is not Cannon
            //condition.AttributeName = "lastname";
            //condition.Operator = ConditionOperator.Equal;
            //condition.Values = new string[] { "Hecke" };

            //// builds the filter based on the condition
            //FilterExpression filter = new FilterExpression();
            //filter.FilterOperator = LogicalOperator.And;
            //filter.Conditions = new ConditionExpression[] { condition };

            //// Create a LinkEntity to link the owner's information to the account
            //LinkEntity link = new LinkEntity();

            //// Set the LinkEntity's Properties
            //link.LinkCriteria = filter;

            //// Set the linking entity to be the account
            //link.LinkFromEntityName = EntityName.account.ToString();

            //// Set the linking attribute to be the owninguser
            //link.LinkFromAttributeName = "owninguser";

            //// Set the attribute being linked to to be the systemuserid
            //link.LinkToAttributeName = "systemuserid";

            //// Set the entity being linked to to be the systemuser
            //link.LinkToEntityName = EntityName.systemuser.ToString();

            //// Create the Query
            //QueryExpression query = new QueryExpression();

            //// Set the Query's Properties
            //query.EntityName = EntityName.account.ToString();
            //query.ColumnSet = cols;
            //query.LinkEntities = new LinkEntity[] { link };

            //// Create the Request Object
            //RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();

            //// Set the Request Object's Properties
            //retrieve.Query = query;

            //// Execute the Request
            //RetrieveMultipleResponse retrieved2 = (RetrieveMultipleResponse)service.Execute(retrieve);
            //#endregion

            //#region check success

            //bool success = false;

            //if ((retrieved1.BusinessEntityCollection.EntityName.ToLower().Equals("account")) &&
            //    (retrieved2.BusinessEntityCollection.EntityName.ToLower().Equals("account")))
            //{
            //    success = true;
            //}

            #endregion

            //for (int i = 0; i < retrieved2.BusinessEntityCollection.BusinessEntities.Length; i++)
            //{
            //    account a = (account)retrieved2.BusinessEntityCollection.BusinessEntities[i];
            //    Console.WriteLine("account name = {0}", a.name);
            //}

            
        }


    }
}
